﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mimoza.Plugins.DisplaySettings
{
    public class Virtual_PC_ExecutePlugin : BaseExecutePlugin
    {
        #region BaseExecutePlugin Members

        public override string Id
        {
            get { return this.ToString(); }
        }

        public override bool Add(Mimoza.ObjectLayer.Policy policy, DisplayResolution data)
        {
            return Apply(policy, data);
        }

        public override bool Remove(Mimoza.ObjectLayer.Policy policy, DisplayResolution data)
        {
            return false;
        }

        public override bool Update(Mimoza.ObjectLayer.Policy policy, DisplayResolution data)
        {
            return Apply(policy, data);
        }

        #endregion

        bool Apply(Mimoza.ObjectLayer.Policy policy, DisplayResolution data)
        {
#if WindowsCE
            const string ConfigFilePath = "\\Жесткий Диск\\AUTOEXEC.BAT";
#else
            const string ConfigFilePath = "AUTOEXEC.BAT";
#endif
            const string ResValueText = "set RES=/L:";

            string resolutionNewString = ResValueText + GetSettingsString(data);

            List<string> lineList = ReadAllLines(ConfigFilePath);
            int lineIdx = lineList.FindIndex(x => (x.StartsWith(ResValueText) && x != resolutionNewString));
            if (lineIdx > 0) 
            {
                lineList[lineIdx] = resolutionNewString;
                WriteAllLines(ConfigFilePath, lineList);

                return true;
            }
            else 
                return false;
        }

        string GetSettingsString(DisplayResolution data)
        {
            return data.Width.ToString() + "x" + data.Height.ToString() + "x" + data.ColorDepthAsInt.ToString();
        }

        List<string> ReadAllLines(string filePath)
        {
            List<string> res = new List<string>();

            using (StreamReader reader = new StreamReader(filePath))
	        {
	            string line;
	            while ((line = reader.ReadLine()) != null)
	            {
                    res.Add(line);
                }
	        }

            return res;
        }

        void WriteAllLines(string filePath, List<string> lineList)
        {
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                foreach (string line in lineList)
                {
                    writer.WriteLine(line);
                }
            }
        }
    }
}
